package com.nus.chat;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.muc.MultiUserChat;

import com.nus.OptionsActivity;
import com.nus.R;

import java.util.ArrayList;

public class XMPPClient extends Activity {

	private ArrayList<String> messages = new ArrayList<String>();
	private Handler mHandler = new Handler();
	private EditText mRecipient;
	private EditText mSendText;
	private ListView mList;
	private XMPPConnection connection;
	// private Chat chat;
	private MultiUserChat muc;
	private String to;
	private TextView title1;
     private ArrayAdapter<String> adapter;
	/**
	 * Called with the activity is first created.
	 */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		Log.i("XMPPClient", "onCreate called");
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.chatroom);
		
		//setContentView(setContentView(R.layout.chatroom);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
		title1 = (TextView) findViewById(R.id.titleheader);
        title1.setText("NUS Connect");
		mSendText = (EditText) this.findViewById(R.id.sendText);
		Log.i("XMPPClient", "mSendText = " + mSendText);
		mList = (ListView) this.findViewById(R.id.listMessages);
		Log.i("XMPPClient", "mList = " + mList);
		//setListAdapter();
		adapter = new ArrayAdapter<String>(this,
				R.layout.multi_line_list_item);
		mList.setAdapter(adapter);
		
	

		// Set a listener to send a chat text message
		Button send = (Button) this.findViewById(R.id.send);
		send.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// to = mRecipient.getText().toString();
				to = "nus@nus.rohit-pc";
				final String text = mSendText.getText().toString();

				Log.i("XMPPClient", "Sending text [" + text + "] to [" + to
						+ "]");
				Message msg = new Message(to, Message.Type.groupchat);
				msg.setBody(OptionsActivity.uname + ":" + text);

				try {
					muc.sendMessage(msg);
					// chat.sendMessage(text);
				} catch (XMPPException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				setListAdapter();

			}
		});
		OptionsActivity.pd.dismiss();
		setConnection();
	}

//	 public boolean onKeyDown(int keyCode, KeyEvent event)  {
//	        if (keyCode == KeyEvent.KEYCODE_BACK) {
//	        	this.connection.disconnect();
//				this.finish();
//	        }
//			return false;
//	        	
//	        }
	@Override
	protected void onStop() {
	    super.onStop();
	    mList.setVisibility(View.GONE);
	}

	@Override
	protected void onRestart() {
	    super.onRestart();
	    mList.setVisibility(View.VISIBLE);
	}
	/**
	 * Called by Settings dialog when a connection is establised with the XMPP
	 * server
	 * 
	 * @param connection
	 */
	public void setConnection() {
		this.connection = ChatApis.setupConnection();
		if (connection != null) {
			connection.getChatManager();
			muc = new MultiUserChat(connection, "nus@nus.rohit-pc");
			try {
				muc.join(connection.getUser());
			} catch (XMPPException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			muc.addMessageListener(new PacketListener() {

				@Override
				public void processPacket(Packet arg0) {
					// TODO Auto-generated method stub
					// messages.add(fromName + ":");
					Message msg1 = (Message) arg0;
					messages.add(msg1.getBody());
					// Add the incoming message to the list view
					mHandler.post(new Runnable() {
						public void run() {
							// if(flag){
							setListAdapter();
							// }

						}
					});
				

					Toast.makeText(XMPPClient.this, arg0.toString(),
							Toast.LENGTH_SHORT).show();
					Log.i("XMPPClient", "text aaya [" + arg0.toString()
							+ "] to [" + arg0.toString() + "]");
				}
			});
		
		}
	}

	private void setListAdapter() {
        adapter.clear();
		for(int i=0;i<messages.size();i++){
			adapter.add(messages.get(i));
		}
		adapter.notifyDataSetChanged();
		
	}
}

	 
	